import redis
import urllib.request as ur
import time


# 创建IP池
class ProxyPool():
    def __init__(self):
        self.redis_conn = redis.StrictRedis(
            host='localhost',
            port=6379,
            decode_responses=True,
        )

    # 向redis数据库中设置代理IP
    def set_proxy(self):
        # proxy = ur.urlopen('http://api.ip.data5u.com/dynamic/get.html?order=8e878764f49172adf9f79530c4fb26cf&sep=3').read().decode('utf-8').strip().split(' ')
        # print(proxy)
        proxy_odd = None
        while True:
            proxy_new = ur.urlopen(
                'http://api.ip.data5u.com/dynamic/get.html?order=8e878764f49172adf9f79530c4fb26cf&sep=3').read().decode(
                'utf-8').strip().split(' ')
            if proxy_new != proxy_odd:
                proxy_odd = proxy_new
                self.redis_conn.delete('proxy')
                self.redis_conn.sadd('proxy', *proxy_new)
                print('更换代理IP为', proxy_new)
                time.sleep(2)
            else:
                time.sleep(1)
            # print(proxy)

    # 从redis数据库中提取代理IP
    def get_proxy(self):
        proxy_s = self.redis_conn.srandmember('proxy', 1)
        if proxy_s:
            return proxy_s[0]
        else:
            time.sleep(0.1)
            return self.get_proxy()


if __name__ == '__main__':
    # ProxyPool().set_proxy()
    ProxyPool().get_proxy()
